using System;
using System.Collections.Generic;
using Mall.Api.Entity;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using Mall.Api.ParamModel;
using Newtonsoft.Json;
using Mall.Api.Repository;
using Mall.Api.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authorization;
using Mall.Api.Filters;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;

namespace Mall.Api.Controllers
{
    /// <summary>
    /// 商品管理
    /// </summary>


    [Authorize]
    [ApiController]
    [Route("commodity")]
    public class CommodityController : ControllerBase
    {
        private IRepository<Commodity> _commodity;
        private IRepository<Supplier> _supplier;
        private IRepository<Brand> _brand;
        private IRepository<Class> _class;
        private IRepository<Warehouse> _warehouse;
        private IRepository<CommodityWarehouse> _commodityWarehouse;
        private IRepository<CommodityProperty> _commodityProperty;
        private IRepository<CommodityPropertyValue> _commodityPropertyValue;
        private IRepository<CommodityResources> _commodityResources;
        private IRepository<Resource> _resource;
        private IRepository<CommoditySKU> _commoditySKU;



        private TokenParameter _tokenParameter;
        private readonly IConfiguration _configuration;

        public CommodityController(IConfiguration configuration, IRepository<Commodity> commodity, IRepository<Supplier> supplier,
        IRepository<Brand> brand, IRepository<Class> classes, IRepository<Warehouse> warehouse, IRepository<CommodityWarehouse> commodityWarehouse,
        IRepository<CommodityProperty> commodityProperty, IRepository<CommodityPropertyValue> commodityPropertyValue,
        IRepository<CommodityResources> commodityResources, IRepository<Resource> resource, IRepository<CommoditySKU> commoditySKU)
        {
            _configuration = configuration;
            _commodity = commodity;
            _supplier = supplier;
            _warehouse = warehouse;
            _commodityWarehouse = commodityWarehouse;
            _commodityProperty = commodityProperty;
            _commodityPropertyValue = commodityPropertyValue;
            _commodityResources = commodityResources;
            _commoditySKU = commoditySKU;
            _resource = resource;
            _class = classes;
            _brand = brand;
            _tokenParameter = _configuration.GetSection("TokenParameter").Get<TokenParameter>();
        }

        /// <summary>
        /// 获取商品列表
        /// </summary>
        /// <param name="pager"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        public dynamic Get([FromQuery] Pager pager)
        {//get请求默认从uri从获取参数，所以此处应该加上FromQuery的特性才能正确获得参数
            var pageIndex = pager.PageIndex;
            var pageSize = pager.PageSize;





            // 获得所有满足条件的记录
            // var users = _usersRespository.Table.Where(x => x.IsDeleted == false);

            var commodity = from commoditys in _commodity.Table
                            join suppliers in _supplier.Table on commoditys.SupplierId equals suppliers.Id
                            join brands in _brand.Table on suppliers.BrandId equals brands.Id
                            join classes in _class.Table on commoditys.ClassId equals classes.Id
                            where commoditys.IsDeleted == false
                            select new
                            {
                                Id = commoditys.Id,
                                ProductName = commoditys.ProductName,
                                Price = commoditys.Price,
                                ClassName = classes.ClassName,
                                BrandName = brands.BrandName,
                                StoreName = suppliers.StoreName,
                                IsActived = commoditys.IsActived,
                                IsDeleted = commoditys.IsDeleted,
                                CreatedTime = commoditys.CreatedTime,
                                CoverPicture = commoditys.CoverPicture,
                                Introduction = commoditys.Introduction




                            };

            if (!string.IsNullOrEmpty(pager.KeyWord))
            {
                commodity = commodity.Where(u => u.ProductName.Contains(pager.KeyWord) || u.ClassName.Contains(pager.KeyWord));
            }




            // 对获得的记录分页
            var u = commodity.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            // 返回的数据里，带有数据和分页信息
            var res = new
            {
                Code = 1000,
                Data = new { Data = u, Pager = new { pageIndex, pageSize, rowsTotal = commodity.Count() } },
                Msg = "获取商品列表成功^_^"
            };
            return res;
        }

        /// <summary>
        /// 根据指定id查找数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("{id}")]
        public dynamic Get(int id)
        {
            var commodity = _commodity.GetById(id);

            if (commodity == null)
            {
                return new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "指定商品不存在"
                };

            }
            return new
            {
                Code = 200,
                Data = commodity,
                Msg = "获取商品列表成功^_^"
            };

        }






        /// <summary>
        /// 添加商品
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>

        [HttpPost]
        public async Task<string> Post(NewCommodity model)
        {
            string str = Guid.NewGuid().ToString().Replace("-", "").ToLower().Substring(0, 6);
            var productCode = str;
            var productName = model.ProductName.Trim();
            var introduction = model.Introduction.Trim();
            var productsId = model.Id;
            var classId = model.ClassId;
            // var supplierId = model.SupplierId;
            var price = model.Price;
            var originalPrice = model.OriginalPrice;
            var brandName = model.BrandName;
            var className = model.ClassName;
            var warehouseName = model.WarehouseName;
            // var brandId = _brand.Table.Where(b => b.BrandName==brandName).FirstOrDefault().Id;
            var classesId = _class.Table.Where(c => c.ClassName == className).FirstOrDefault().Id;
            var warehouseId = _warehouse.Table.Where(w => w.WarehouseName == warehouseName).FirstOrDefault().Id;
            // var productId = _commodity.Table.Where(p => p.ProductName == productName).FirstOrDefault().Id;
            // var resourceName = model.ResourceName;
            // var resourceId = model.ResourceId;
            var Properties = model.Properties;
            // var commodityPropertyId = _commodityProperty.Table.Where(c => c.PropertyName == propertyName).FirstOrDefault().Id;
            // var commodityPropertyId = model.CommodityPropertyId;
            // var commodityPropertyValueId = model.CommodityPropertyValueId;       
            var propertyValue = model.PropertyValue;
            // var commodityPropertyValueId = _commodityPropertyValue.Table.Where(cid => cid.PropertyValue == propertyValue).FirstOrDefault().Id;
            var vauluPrice = model.ValuePrice;
            var coverPicture = model.CoverPicture;
            var arr = new List<int>();





            var claims = base.HttpContext.AuthenticateAsync().Result
           .Principal.Claims.FirstOrDefault().Subject.Claims;


            var supplierId = claims.FirstOrDefault(c => c.Type == "supplierId")?.Value;



            var commodity = new Commodity
            {
                ProductCode = productCode,
                ProductName = productName,
                Introduction = introduction,
                CoverPicture = coverPicture,
                Class = _class.Table.Single(c => c.Id == classesId),
                Supplier = _supplier.Table.Single(s => s.Id == int.Parse(supplierId)),
                Price = price,
                OriginalPrice = originalPrice


            };
            _commodity.Insert(commodity);


            var commodityWarehouse = new CommodityWarehouse
            {
                Commodity = _commodity.Table.Single(c => c.Id == commodity.Id),
                Warehouse = _warehouse.Table.Single(w => w.Id == warehouseId),
                AddNumber = model.AddNumber
            };

            _commodityWarehouse.Insert(commodityWarehouse);
            var w = _warehouse.GetById(warehouseId);
            w.QuantityInStock += commodityWarehouse.AddNumber;
            _warehouse.Update(w);

            var CommoditySKUList = new List<CommoditySKU>();
            var commodityPropertyValues = new List<CommodityPropertyValue>();

            foreach (Property item in Properties)
            {
                var cp = _commodityProperty.Table.Where(cp => cp.PropertyName == item.PropertyName).FirstOrDefault();

                foreach (PropertyValue p in item.PropertyValues)
                {
                    var cpv = new CommodityPropertyValue
                    {
                        CommodityProperty = cp,
                        ValuePrice = Convert.ToDouble(p.Price),
                        PropertyValue = p.Value
                    };
                    commodityPropertyValues.Add(cpv);

                    var commoditySKU = new CommoditySKU
                    {
                        Commodity = _commodity.Table.Single(ct => ct.Id == commodity.Id),
                        CommodityProperty = _commodityProperty.Table.Single(c => c.Id == cp.Id),
                        CommodityPropertyValue = cpv
                    };
                    CommoditySKUList.Add(commoditySKU);

                }

            }

            await _commodityPropertyValue.InsertBulkAsync(commodityPropertyValues);
            await _commoditySKU.InsertBulkAsync(CommoditySKUList);


            return JsonHelper.Serialize(new
            {
                Code = 200,
                Data = commodity,
                Msg = "添加商品成功！"
            });





        }





        /// <summary>
        /// 真删除指定商品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public dynamic Delete(int id)
        {
            var user = _commodity.GetById(id);
            if (user != null)
            {
                _commodity.Delete(id);
                return new
                {
                    Code = 200,
                    Msg = string.Format("删除指定id为{0}的商品成功", id)
                };
            }
            else
            {
                return new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "指定Id的商品不存在，请确认后重试"
                };
            }

        }




        /// <summary>
        /// 修改商品信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <returns></returns>

        [HttpPut("{id}")]
        public dynamic Put(int id, NewCommodity model)
        {
            var commodity = _commodity.GetById(id);


            if (commodity != null)
            {
                commodity.ProductName = model.ProductName;
                commodity.Introduction = model.Introduction;
                commodity.Price = model.Price;
                commodity.OriginalPrice = model.OriginalPrice;



                commodity.UpdatedTime = DateTime.Now;
                _commodity.Update(commodity);
                return JsonHelper.Serialize(new
                {
                    Code = 200,
                    Data = commodity,
                    Msg = string.Format("你修改商品的id为：{0}，已经修改成功，请注意查收", id)
                });
            }
            else
            {
                return JsonHelper.Serialize(new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "指定Id的商品不存在，请确认后重试"
                });
            }
        }











    }

}